package com.hq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hq.bean.Product;
import com.hq.bean.Users;
import com.hq.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import util.FileUploadUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ProductController {
    @Resource
    private ProductService productService;

    @RequestMapping("list.do")
    public Object list(Model model, @RequestParam(value = "cpage", defaultValue = "1") Integer cpage,
                       String mohu1) {
        Map map = new HashMap();
        map.put("mohu1", mohu1);
        PageHelper.startPage(cpage, 3);
        List list = productService.list(map);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("map", map);
        return "list";
    }

    @RequestMapping("add.do")
    @ResponseBody
    public Object add(Product product, @RequestParam("photo") MultipartFile photo, Integer[] bids, HttpSession session) {
        if (photo.getOriginalFilename().length() > 0) {
            String upload = FileUploadUtil.load(session, photo, "upload");
            product.setImage(upload);
        }
        int i = productService.add(product, bids);
        return i;
    }

    @RequestMapping("toadd.do")
    public String toadd() {
        return "add";
    }

    @RequestMapping("baseList.do")
    @ResponseBody
    public Object baseList() {
        List list = productService.baseList();
        return list;
    }

    @RequestMapping("login.do")
    public String  login(Users users,HttpSession session){
        Users login = productService.login(users);
        if (login!=null){
            session.setAttribute("users",login);
            return "redirect:list.do";
        }else {
            return "redirect:index.jsp";
        }
    }
}